package com.das.mechanic_alone.mvp.view.alone.fragment;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_alone.mvp.contract.alone.AloneFragmentContract;
import com.das.mechanic_alone.mvp.presenter.alone.AlonefragmentPresnter;
import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.alone.X3AloneTitleAdapter;
import com.das.mechanic_base.adapter.common.X3AloneServiceItemAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseFragment;
import com.das.mechanic_base.bean.alone.ServiceHeaderBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.bean.main.HomeMainCarBean;
import com.das.mechanic_base.utils.X3AloneServiceSearchUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.widget.X3BottomAffirmMileDialog;
import com.das.mechanic_base.widget.X3NewBottomMileOrTimeDialog;
import com.das.mechanic_base.widget.X3PointDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import static com.das.mechanic_base.app.X3Constent.CODE_ALONE_CHANGE_NEED_UPDATE;

public class X3AloneServiceFragment extends X3BaseFragment<AlonefragmentPresnter> implements AloneFragmentContract.View, X3AloneTitleAdapter.IOnShowTilte, X3AloneServiceItemAdapter.IOnClickService, X3NewBottomMileOrTimeDialog.IOnAffirmSelect {
    RecyclerView rlv_second;
    RecyclerView rlv_service;

    List<ServiceHeaderBean.ShopCategoryEntityBean> mList;
    private X3AloneTitleAdapter titleAdapter;
    private X3AloneServiceItemAdapter itemAdapter;
    private HashMap<String, Integer> titleMap;
    private List<AloneServiceListBean> cacheList;
    private long questionBaseId,questionOptionId;
    private long lastVisibleIndex = 0;
    private AloneServiceListBean serviceListBean;
    private String decTitle;
    private List<AloneServiceListBean> newCacheList;
    private boolean needUpdateMile;
    private long workBaseId;
    private HomeMainCarBean carBean;
    private double newPerMiles;
    private double newCurrentMile;
    private X3NewBottomMileOrTimeDialog mileOrTimeDialog;
    private AloneServiceListBean changeServiceBean;
    private X3PointDialog delDialog;
    private List<ServiceHeaderBean.ShopCategoryEntityBean> itemList;

    public X3AloneServiceFragment(List<ServiceHeaderBean.ShopCategoryEntityBean> shopCategoryEntityList, long questionBaseId, String decTitle, long questionOptionId) {
        this.mList = shopCategoryEntityList;
        this.questionBaseId = questionBaseId;
        this.questionOptionId = questionOptionId;
        this.decTitle = decTitle;
    }

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.x3_fragment_alone_service;
    }

    @Override
    protected void initView(View view) {
        rlv_second = view.findViewById(R.id.rlv_second);
        rlv_service = view.findViewById(R.id.rlv_service);

        if (mPresenter != null) {
            mPresenter.getDetectionServiceList(true);
        }
        needUpdateMile = getActivity().getIntent().getBooleanExtra("needUpdateMile", false);
        workBaseId = getActivity().getIntent().getLongExtra("workBaseId", 0L);
        carBean = (HomeMainCarBean)getActivity().getIntent().getSerializableExtra("carBean");

        rlv_second.setLayoutManager(new LinearLayoutManager(getActivity(),RecyclerView.HORIZONTAL,false));
        titleAdapter = new X3AloneTitleAdapter(getActivity());
        rlv_second.setAdapter(titleAdapter);
        titleAdapter.changeTitleList(mList);
        rlv_service.setLayoutManager(new LinearLayoutManager(getActivity()));
        itemAdapter = new X3AloneServiceItemAdapter(getActivity());
        rlv_service.setAdapter(itemAdapter);
        titleAdapter.setiOnShowTilte(this);
        itemAdapter.setiOnClickService(this);
        rlv_service.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if ((getActivity()).isFinishing()) {
                    return;
                }
                if(rlv_service == null){
                    return;
                }

                if(rlv_service.getLayoutManager() == null){
                    return;
                }

                int visiblePosition = ((LinearLayoutManager) rlv_service.getLayoutManager()).findFirstVisibleItemPosition();
                if (titleMap == null) {
                    return;
                }
                int visibleIndex = -1;
                for (String key : titleMap.keySet()) {
                    if (visiblePosition >= titleMap.get(key)) {
                        visibleIndex++;
                    }
                }
                if (visibleIndex == -1) {
                    return;
                }
                if (lastVisibleIndex == visibleIndex) {
                    return;
                }
                if (titleAdapter != null) {
                    titleAdapter.changeTitleSelectList(visibleIndex);
                    lastVisibleIndex = visibleIndex;
                }
            }
        });
    }

    private void initItemAdapter(List<ServiceHeaderBean.ShopCategoryEntityBean> sList) {
        this.itemList = sList;
        List<ServiceHeaderBean.ShopCategoryEntityBean.ServiceBaseEntityBean> baseList = new ArrayList<>();
        titleMap = new HashMap<>();
        if (!X3StringUtils.isListEmpty(itemList)) {
            for (int i = 0; i < itemList.size(); i++) {
                if (!titleMap.containsKey(itemList.get(i).getName())) {
                    titleMap.put(itemList.get(i).getName(),baseList.size());
                }
                List<ServiceHeaderBean.ShopCategoryEntityBean.ServiceBaseEntityBean> serviceBaseEntityList = itemList.get(i).getServiceBaseEntityList();
                if (X3StringUtils.isListEmpty(serviceBaseEntityList)) {
                    break;
                }
                baseList.addAll(serviceBaseEntityList);
            }
        }

        for (int i = 0; i < baseList.size(); i++) {
            ServiceHeaderBean.ShopCategoryEntityBean.ServiceBaseEntityBean serviceBean = baseList.get(i);
            if (X3StringUtils.isListEmpty(cacheList)) {
                baseList.remove(i);
                serviceBean.setTouched(false);
                baseList.add(i,serviceBean);
                continue;
            }
            String sn = serviceBean.getSn();
            int haveIndex = -1;
            for (int j = 0; j < cacheList.size(); j++) {
                if (cacheList.get(j).getTouchServiceSn().equals(sn)) {
                    haveIndex = j;
                    break;
                }
            }
            if (haveIndex == -1) {
                baseList.remove(i);
                serviceBean.setTouched(false);
                baseList.add(i,serviceBean);
            }else {
                baseList.remove(i);
                serviceBean.setRecommendSafeMiles(cacheList.get(haveIndex).getRecommendSafeMiles());
                serviceBean.setTouched(true);
                serviceBean.setRemildType(cacheList.get(haveIndex).getReductionType());
                serviceBean.setWarningDate(cacheList.get(haveIndex).getWarningDate());
                baseList.add(i,serviceBean);
            }
        }

        if (itemAdapter != null) {
            itemAdapter.changeServiceItem(baseList);
        }
    }

    @Override
    protected AlonefragmentPresnter createPresenter() {
        return new AlonefragmentPresnter();
    }


    @Override
    public void iOnShowTitleItem(String title) {
        if (titleMap == null) {
            return;
        }
        int index = titleMap.get(title);
        if(rlv_service == null){
            return;
        }
        if(rlv_service.getLayoutManager() == null){
            return;
        }

        ((LinearLayoutManager)rlv_service.getLayoutManager()).scrollToPositionWithOffset(index,0);
    }

    @Override
    public void iOnCuteService(boolean isCute, ServiceHeaderBean.ShopCategoryEntityBean.ServiceBaseEntityBean serviceBean, int position) {
        serviceListBean = X3AloneServiceSearchUtils.searchAloneServiceBean(cacheList,serviceBean.getSn());

        if (isCute) {
            /**
             * 将这个服务项目从缓存中去除
             */
            if (serviceListBean == null) {
                if (mPresenter != null) {
                    mPresenter.getDetectionServiceList(true);
                }
                return;
            }

            List<AloneServiceListBean.IdBean> idBeans = serviceListBean.getQuestionAndOptionIdVOList();

            if (!X3StringUtils.isListEmpty(idBeans)) {
                Iterator<AloneServiceListBean.IdBean> iterator = idBeans.iterator();
                while (iterator.hasNext()) {
                    AloneServiceListBean.IdBean next = iterator.next();
                    if (next.getOptionsId() == 0) {
                        iterator.remove();
                    }
                }
                List<Long> touchQuestionBaseIdList = new ArrayList<>();
                for (AloneServiceListBean.IdBean idBean : idBeans) {
                    touchQuestionBaseIdList.add(idBean.getQuestionBaseId());
                }

                serviceListBean.setTouchQuestionBaseIdList(touchQuestionBaseIdList);
                serviceListBean.setQuestionAndOptionIdVOList(idBeans);
            }
            deleteService(serviceListBean);
        }else {
            if (!needUpdateMile) {
                serviceListBean = addServiceItem(serviceBean, serviceListBean);
                iOnShowChangeServiceOne(serviceListBean, serviceListBean.getReductionType());
            }else {
                // 否则需要先确认总里程和日均里程
                X3BottomAffirmMileDialog mileDialog = new X3BottomAffirmMileDialog(getActivity());
                mileDialog.show();
                mileDialog.setWorkBaseId(workBaseId,carBean);
                mileDialog.setiOnClickAffirmMiles((currentMiles1, perMiles1) -> {
                    // 确认完总里程和日均里程了
                    needUpdateMile = false;

                    newPerMiles = Double.parseDouble(X3StringUtils.formatDouble(perMiles1));
                    newCurrentMile = Double.parseDouble(X3StringUtils.formatDouble(currentMiles1));

                    CameraBean cameraBean = new CameraBean();
                    cameraBean.currentMiles = newCurrentMile;
                    cameraBean.perMiles = newPerMiles;
                    EventBus.getDefault().post(new CameraBean(CODE_ALONE_CHANGE_NEED_UPDATE,cameraBean));

                    serviceBean.setCurrentMiles(newCurrentMile);
                    serviceBean.setPerMiles(newPerMiles);

                    serviceListBean = addServiceItem(serviceBean, serviceListBean);

                    if (mPresenter != null) {
                        mPresenter.getDetectionServiceList(false);
                    }
                    if (itemAdapter != null) {
                        itemAdapter.refreshMiles(newCurrentMile, newPerMiles);
                    }

                    iOnShowChangeServiceOne(serviceListBean, serviceListBean.getReductionType());
                });
            }
        }
    }

    /**
     * 删除非系统推荐的服务
     * @param serviceListBean
     */
    private void deleteService(AloneServiceListBean serviceListBean) {
        List<Long> touchQuestionBaseIdList = serviceListBean.getTouchQuestionBaseIdList();
        List<String> descriptionList = serviceListBean.getTouchQuestionBaseDescriptionList();
        if (!X3StringUtils.isListEmpty(descriptionList) && descriptionList.contains(decTitle)) {
            descriptionList.remove(descriptionList.indexOf(decTitle));
        }

        if (X3StringUtils.isListEmpty(touchQuestionBaseIdList)) {
            Iterator<AloneServiceListBean> iterator = cacheList.iterator();
            while (iterator.hasNext()) {
                AloneServiceListBean next = iterator.next();
                if (next.getTouchServiceSn().equals(serviceListBean.getTouchServiceSn())) {
                    iterator.remove();
                }
            }
        }else {
            serviceListBean.setTouchQuestionBaseDescriptionList(descriptionList);
            serviceListBean.setTouchQuestionBaseIdList(touchQuestionBaseIdList);
            cacheList = X3AloneServiceSearchUtils.replaceAloneServiceBean(cacheList,serviceListBean.getTouchServiceSn(),serviceListBean);
        }
        iOnPickerDismiss();

        if (mPresenter != null) {
            mPresenter.saveDetectionService(cacheList);
        }
    }

    @Override
    public void iOnShowChangeService(String sn, String remindType, double currentMiles, double perMiles) {
        changeServiceBean = X3AloneServiceSearchUtils.searchAloneServiceBean(cacheList,sn);
        changeServiceBean.setCurrentMiles(currentMiles);
        changeServiceBean.setPerMiles(perMiles);

        modifyMileOrTime(changeServiceBean,remindType);
    }

    @Override
    public void iOnShowDelete(int position, String sn) {
        AloneServiceListBean serviceListBean = X3AloneServiceSearchUtils.searchAloneServiceBean(cacheList,sn);
        if (serviceListBean == null) {
            return;
        }

        List<String> touchIdList = serviceListBean.getTouchQuestionBaseDescriptionList();
        if (X3StringUtils.isListEmpty(touchIdList)) {
            touchIdList = new ArrayList<>();
        }

        List<AloneServiceListBean.IdBean> idBeans = serviceListBean.getQuestionAndOptionIdVOList();

        if (touchIdList.size() - 1 <= 0) {
            delDialog = new X3PointDialog(getContext(),"",getString(R.string.x3_delete_add_service),getString(R.string.x3_cancel_info),getString(R.string.x3_affirm_info));
            delDialog.show();
            delDialog.setRightClick(view -> {
                delDialog.dismiss();
                if (!X3StringUtils.isListEmpty(idBeans) && idBeans.size() > 0) {
                    AloneServiceListBean.IdBean idBean = idBeans.get(0);
                    if (idBean.getOptionsId() != 0) {
                        X3ToastUtils.showMessage(getString(R.string.no_can_delete_item));
                    }else {
                        if (itemAdapter != null) {
                            itemAdapter.deleteService(position,true,true);
                        }
                    }
                }else {
                    if (itemAdapter != null) {
                        itemAdapter.deleteService(position,true,true);
                    }
                }
            });
        }else {
            if (touchIdList.contains(decTitle)) {
                touchIdList.remove(touchIdList.indexOf(decTitle));
            }
            String serviceName = "";
            for (int i = 0; i < touchIdList.size(); i++) {
                if (i == 0) {
                    serviceName = touchIdList.get(i);
                }else {
                    serviceName = serviceName + "," + touchIdList.get(i);
                }
            }
            delDialog = new X3PointDialog(getContext(),"",String.format(getString(R.string.x3_delete_all_add_service),serviceName),getString(R.string.x3_no_tips),getString(R.string.x3_yes_tips));
            delDialog.show();
            delDialog.setLeftClick(view -> {
                delDialog.dismiss();

                if (!X3StringUtils.isListEmpty(idBeans)) {
                    boolean isSystem = false;
                    for (int i = 0; i < idBeans.size(); i++) {
                        if (idBeans.get(i).getQuestionBaseId() == questionBaseId && idBeans.get(i).getOptionsId() == questionOptionId) {
                            isSystem = true;
                            break;
                        }
                    }
                    if (isSystem) {
                        X3ToastUtils.showMessage(getString(R.string.no_can_delete_item));
                    }else {
                        if (itemAdapter != null) {
                            itemAdapter.deleteService(position,true,false);
                        }
                    }

                }else {
                    if (itemAdapter != null) {
                        itemAdapter.deleteService(position,true,false);
                    }
                }
            });
            delDialog.setRightClick(view -> {
                delDialog.dismiss();
                Iterator<AloneServiceListBean.IdBean> iterator = idBeans.iterator();
                while (iterator.hasNext()) {
                    AloneServiceListBean.IdBean next = iterator.next();
                    if (next.getOptionsId() == 0) {
                        iterator.remove();
                    }
                }
                serviceListBean.setQuestionAndOptionIdVOList(idBeans);
                X3AloneServiceSearchUtils.replaceAloneServiceBean(cacheList,sn,serviceListBean);

                iOnPickerDismiss();
                if (mPresenter != null) {
                    mPresenter.saveDetectionService(cacheList);
                }
                if (itemAdapter != null) {
                    itemAdapter.deleteAllService(position);
                }
            });
        }
    }

    @Override
    public void iOnAffirmMiles(AloneServiceListBean listBean) {
        boolean isHave = false;
        newCacheList = cacheList;
        for (int i = 0; i < newCacheList.size(); i++) {
            AloneServiceListBean aloneServiceListBean = newCacheList.get(i);
            if (aloneServiceListBean.getTouchServiceSn().equals(listBean.getTouchServiceSn())) {
                isHave = true;
                newCacheList.remove(i);
                newCacheList.add(i,listBean);
                break;
            }
        }
        if (!isHave) {
            newCacheList.add(listBean);
        }
        iOnPickerDismiss();
        mPresenter.saveDetectionService(newCacheList);
        if (itemAdapter != null) {
            itemAdapter.changeMilesService(changeServiceBean);
        }
    }

    public void iOnPickerDismiss() {
        CameraBean cameraBean = new CameraBean(X3Constent.CODE_ALONE_ADD_SERVICE_REQUEST,cacheList);
        EventBus.getDefault().post(cameraBean);
    }

    @Override
    public long providerWorkBaseId() {
        return getActivity().getIntent().getLongExtra("workBaseId", 0L);
    }

    @Override
    public void searchAloneCache() {
        if (mPresenter != null) {
            mPresenter.getDetectionServiceList(false);
        }
    }

    @Override
    public void getServiceList(List<AloneServiceListBean> cList,boolean isStart) {
        this.cacheList = cList;
        if (isStart) {
            initItemAdapter(mList);
            return;
        }
        iOnPickerDismiss();
    }

    private AloneServiceListBean addServiceItem(ServiceHeaderBean.ShopCategoryEntityBean.ServiceBaseEntityBean serviceBean,AloneServiceListBean serviceListBean1) {
        List<Long> idList = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        List<AloneServiceListBean.IdBean> idBeans = new ArrayList<>();
        AloneServiceListBean newServiceBean = serviceListBean1;
        if (newServiceBean == null) {
            newServiceBean = new AloneServiceListBean();
            newServiceBean.setWorkBaseId(workBaseId);
            newServiceBean.setRecommendSafeMiles(serviceBean.getRecommendSafeMiles());
            newServiceBean.setTouchServiceBaseName(serviceBean.getName());
            newServiceBean.setTouchServiceSn(serviceBean.getSn());
            newServiceBean.setCurrentMiles(serviceBean.getCurrentMiles());
            newServiceBean.setPerMiles(serviceBean.getPerMiles());
            newServiceBean.setWarningDate(serviceBean.warningDate);
            newServiceBean.setReductionType(serviceBean.getRemildType());
            newServiceBean.setSeleced(serviceBean.isTouched());

            if (!idList.contains(questionBaseId)) {
                idList.add(questionBaseId);
            }
            titleList.add(decTitle);
            idBeans.add(new AloneServiceListBean.IdBean(questionBaseId,0));
            newServiceBean.setSystemList(new ArrayList<>());
            newServiceBean.setTouchQuestionBaseDescriptionList(titleList);
            newServiceBean.setQuestionAndOptionIdVOList(idBeans);
            newServiceBean.setTouchQuestionBaseIdList(idList);

        }else {
            idList = newServiceBean.getTouchQuestionBaseIdList();
            titleList = newServiceBean.getTouchQuestionBaseDescriptionList();
            idBeans = newServiceBean.getQuestionAndOptionIdVOList();

            if (X3StringUtils.isListEmpty(idList)) {
                idList = new ArrayList<>();
            }
            if (X3StringUtils.isListEmpty(idBeans)) {
                idBeans = new ArrayList<>();
            }
            if (X3StringUtils.isListEmpty(titleList)) {
                titleList = new ArrayList<>();
            }
            if (!idList.contains(questionBaseId)) {
                idList.add(questionBaseId);
            }
            if (!titleList.contains(decTitle)) {
                titleList.add(decTitle);
            }
            boolean isHave = false;
            for (int i = 0; i < idBeans.size(); i++) {
                if (idBeans.get(i).getQuestionBaseId() == questionBaseId) {
                    isHave = true;
                    break;
                }
            }
            if (!isHave) {
                idBeans.add(new AloneServiceListBean.IdBean(questionBaseId,0));
            }

            newServiceBean.setTouchQuestionBaseDescriptionList(titleList);
            newServiceBean.setTouchQuestionBaseIdList(idList);
        }
        return newServiceBean;
    }
    public void iOnShowChangeServiceOne(AloneServiceListBean changeServiceBean,String remindType) {
        this.changeServiceBean = changeServiceBean;
        modifyMileOrTime(changeServiceBean,remindType);
    }

    private void modifyMileOrTime(AloneServiceListBean changeServiceBean,String remindType) {
        if (changeServiceBean == null) {
            return;
        }
        if (changeServiceBean.getCurrentMiles() <= 0 && changeServiceBean.getPerMiles() <= 1) {
            changeServiceBean.setPerMiles(newPerMiles);
            changeServiceBean.setCurrentMiles(newCurrentMile);
        }
        mileOrTimeDialog = new X3NewBottomMileOrTimeDialog(getActivity(),1);
        mileOrTimeDialog.show();
        mileOrTimeDialog.showCurrentMile(changeServiceBean,remindType);
        mileOrTimeDialog.setiOnAffirmSelect(this);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetPictureOrVideo(CameraBean cameraBean) {
        if (cameraBean == null) {
            return;
        }
        switch ((int) cameraBean.resultCode) {
            case X3Constent.CODE_ALONE_ADD_SERVICE_REQUEST:
                if (cameraBean.cameraData == null) {
                    return;
                }
                cacheList = (List<AloneServiceListBean>) cameraBean.cameraData;
                initItemAdapter(itemList);
                break;
            case CODE_ALONE_CHANGE_NEED_UPDATE:
                if (cameraBean.cameraData == null) {
                    return;
                }
                CameraBean mileBean = (CameraBean) cameraBean.cameraData;
                needUpdateMile = false;
                newCurrentMile = mileBean.currentMiles;
                newPerMiles = mileBean.perMiles;

                break;
        }
    }
}
